package com.hourupdate.network.server;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import org.apache.log4j.Logger;

public class Connection {
	static final Logger logger = Logger.getLogger(Connection.class);
    private Socket         _connect;
    private PrintWriter    _writer;
    private BufferedReader _reader;
    private boolean        _isServer;
    
    public Connection(Socket socket) {
        this(socket, true);
    }
    
    public Connection(Socket socket, boolean isServer) {
        try {
            _connect = socket;
            _writer  = new PrintWriter(
                        new OutputStreamWriter(
                            _connect.getOutputStream()));
            _reader  = new BufferedReader(
                        new InputStreamReader(
                            _connect.getInputStream()));

            _isServer = isServer;
        }
        catch (IOException e) {
        	logger.error(e.getMessage());
        }
    }
    
    public String readLine() {
        try {
            return _reader.readLine();
        }
        catch (IOException e) {
        	logger.error(e.getMessage());
            return null;
        }
    }
    
    public void writeLine(String data) {
        _writer.println(data);
        _writer.flush();
    }
    
    public void close() {
        try {
            if (_isServer) {
                _reader.close();
                _writer.close();
            }
            else {
                _writer.close();
                _reader.close();
            }

            _connect.close();
        }
        catch (IOException e) {
            logger.error(e.getMessage());
        }
    }
}